package com.lhj.es.util;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tencent.wework.Finance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author linghaijin
 * @date 2021-09-26 10:24
 */
public class WeSessionBackUpUtil {

    private final static Logger logger = LoggerFactory.getLogger(WeSessionBackUpUtil.class);
    private static long sdk = 0;
    private static long timeout = 10 * 60 * 1000;

    public static void initSDK() {
        if (sdk == 0) {
            sdk = Finance.NewSdk();
            Finance.Init(sdk, "ww3a4b6f1af19c38ce", "QqkpWR4VtqVmWyz9JLoyLZJ5lJcJxygq7rLFNyYE09o");
        }
    }


    public static void main(String[] args) {
        initSDK();
        //每次使用GetChatData拉取存档前需要调用NewSlice获取一个slice，在使用完slice中数据后，还需要调用FreeSlice释放。
        long slice = Finance.NewSlice();
        long ret = Finance.GetChatData(sdk, 934, 10, "", "",timeout,slice);
        if (ret != 0) {
            logger.warn("获取存档消息 " + ret);
        } else {
            String content = Finance.GetContentFromSlice(slice);
            logger.info(content);
            JsonArray jsonElements = JsonParser.parseString(content).getAsJsonObject().get("chatdata").getAsJsonArray();
            if (null != jsonElements && jsonElements.size() > 0) {
                long newSlice = Finance.NewSlice();
                for (JsonElement jsonElement : jsonElements) {
                    try {
                        JsonObject jsonObject = jsonElement.getAsJsonObject();
                        int version = jsonObject.get("publickey_ver").getAsInt();
                        if (version == 3) {
                            continue;
                        }
                        String key = RSAUtil_PKCS8.getPrivateKey(jsonObject.get("encrypt_random_key").getAsString());
                        int i = Finance.DecryptData(sdk, key, jsonObject.get("encrypt_chat_msg").getAsString(), newSlice);
                        if (i == 0) {
                            String msg = Finance.GetContentFromSlice(newSlice);
                            logger.debug("收到消息存档：{}", msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        Finance.FreeSlice(slice);
    }


}
